<template>
  <div class="height100 bgColor superUserDetail allContainerHeight">
    <el-container  class="height100    domainMainContent containerHeight">
    <el-main class="el-mainContent  height100 overflowYHidden"   ref="managerMain">
      <header_item  :headerArr="headerArr"  @onBtnClick="onBtnClick"/>
    <div  class="width100 overflowy containerContentHeight">
      <el-form ref="form" :model="content" label-position="top" size="mini" :rules="rules"  class="content">
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('username')" prop="name" class="  ">
              <el-input type="text" v-model="content.name" :placeholder="$t('placeholder_enter_content')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="6">
            <el-form-item :label="$t('loginno')" prop="loginno" class="  ">
              <el-input type="text" v-model="content.loginno" :placeholder="$t('placeholder_enter_content')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('password')" prop="loginpwd" class="  ">
              <el-input type="password" v-model="content.loginpwd" @change="changePwd" :placeholder="$t('placeholder_enter_content')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="6">
            <el-form-item :label="$t('confirm_pwd')" prop="confirmpwd" class="  ">
              <el-input type="password" v-model="content.confirmpwd" @change="changePwd" :placeholder="$t('placeholder_enter_content')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('user_type')" v-if="!isFilter" :required="true">
              <el-checkbox v-model="content.superAdmin">{{$t('superAdmin')}}</el-checkbox>
              <el-checkbox v-model="content.domainAdmin">{{$t('tenant_admin')}}</el-checkbox>
              <el-checkbox v-model="content.developer" @change="changeDeveloper">{{$t('develop')}}</el-checkbox>
            </el-form-item>
            <el-form-item :label="$t('author_software_content')" class="   selectTagsText" v-if="isOpen && content.developer">
              <el-select :placeholder="$t('placeholder_select')" multiple v-model="content.applications" v-if="!content.superAdmin">
                <el-option
                  v-for="item in softList"
                  :key="item.id"
                  :label="item.description?item.description:item.name"
                  :value="item.id"
                  :title="item.description?item.description:item.name">
                  <span>{{item.description?item.description:item.name}}</span>
                </el-option>
              </el-select>
              <p v-else class="greyColor">{{$t('super_admin_author')}}</p>
            </el-form-item>
            <el-form-item :label="$t('tenate_admin')" class="   selectTagsText" prop="domains" v-if="isOpen && content.domainAdmin">
              <el-select 
                v-if="!content.superAdmin"
                v-model="content.domains" 
                :disabled="domainDisable" 
                multiple
                :placeholder="$t('placeholder_select')">
                  <el-option
                    v-for="item in domains.datas"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    :title="item.name">
                  <span>{{item.name}}</span>
                  </el-option>
              </el-select>
              <p v-else class="greyColor">{{$t('super_admin_author')}}</p>
            </el-form-item>
            <el-form-item :label="$t('management_scope')" v-if="isFilter">
              <el-form-item :label="$t('belong_domains')" class="  " prop="domains">
                <el-select 
                v-model="content.domains" 
                :disabled="domainDisable" 
                clearable
                filterable
                multiple
                :multiple-limit="1"
                :placeholder="$t('placeholder_select')" 
                @change="changeSelectDoamin"> 
                  <el-option
                    v-for="item in domains.datas"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form-item>
            <el-form-item :label="$t('belong_dept')"  v-if="isFilter" class="   super_select_width" prop="departments">
              <el-select v-model="content.departments" filterable multiple :placeholder="$t('placeholder_select')" no-match-text="无匹配部门">
                <el-option
                  v-for="item in depts.datas"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="4">
            <el-form-item :label="$t('email')" class="  ">
              <el-input type="text" v-model="content.email" :placeholder="$t('placeholder_enter_content')"></el-input>
            </el-form-item>
            <el-form-item :label="$t('fettle')" class="radioPadding0">
              <el-radio-group v-model="content.status">
                <el-radio :label="1">{{$t('effective')}}</el-radio>
                <el-radio :label="0">{{$t('not_effective')}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    </el-main>

  </el-container>
  </div>
</template>

<script>
import {emailCheck, nameCheck,scrollHeight,checkHasIdArr} from "@/utils"
export default {
  components:{
  },
  props: ["detail"],
  created() {
    this.isOpen=true;
    if(this.$store.state.currentUser.isOpenSecurity){
      this.isFilter=true;
    } else {
      this.isFilter=false;
    }
    // 增加一个确认密码项
    if(!this.content.confirmpwd)
      this.content.confirmpwd = ''

    this.content = JSON.parse(JSON.stringify(this.detail));
    // 如果有选中开发者则请求
    if(this.content.developer){
      this.getApplicationsList()
    }
    // 如果有选中授权软件就选中
    if(this.content.domainAdmin){
      this.getDomain()
    }
    this.pwdPre = this.content.loginpwd;
    if(this.content.loginpwd){
      this.content.loginpwd = this.content.loginpwd.substring(0, 8);
      this.content.confirmpwd = this.content.loginpwd;
    }
    this.getDomain();
    this.level=this.$store.state.currentUser.level;
    if(!this.content.id){
      //新建用户
      if(this.$store.state.currentUser.domains && this.$store.state.currentUser.domains.length>0 && this.isOpen){
        //现在登陆的是域级用户，所以新建的时候所属于只读，所属部门必填
        this.content.domains=this.$store.state.currentUser.domains;
        this.domainDisable=true;
        this.deptMust=true;
      }

    }else{
      if(this.content.domains && this.isOpen){
      }
    }
    //关于标题的处理
    this.headerArr={iconfont:'icon-icon_tqyh',content:this.$t('superuser_detail'),btnArr:[{type:'primary',name:'save',label:this.$t('save')},{name:'back',label:this.$t('back')}] }
    
  },
  data() {
    var pwdCheck = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('msg_pwd')));
      } else if (value.toString().length < 6 || value.toString().length > 16) {
        callback(new Error(this.$t('msg_password_length_six')));
      } else {
        callback();
      }
    };
    var deptCheck = (rule, value, callback) => {
      if (!value && this.deptMust) {
        callback(new Error(this.$t('msg_dept_required')));
      }  else {
        callback();
      }
    }
    var domainCheck = (rule, value, callback) => {
      if (!value && this.isFilter) {
        callback(new Error(this.$t('msg_domain_required')));
      }  else {
        callback();
      }
    }


    return {
      scrollHeight:scrollHeight,
      softList: [],
      content: {},
      rules: {
        name: [
          { required: true, message: this.$t('msg_name'), trigger: "blur" },
          { validator: nameCheck, trigger: "blur" }
        ],
        loginno: [
          { required: true, message: this.$t('msg_account'), trigger: "blur" },
          { min: 1, max: 15, message: this.$t('msg_length'), trigger: "blur" },
          { validator: nameCheck, trigger: "blur" }
        ],
        loginpwd: [
          { required: true, message: this.$t('msg_pwd'), trigger: "blur" },
          { validator: pwdCheck, trigger: "blur" }
        ],
        confirmpwd: [
          { required: true, message: this.$t('msg_confirm_pwd'), trigger: "blur" },
        ],
        email: [
          { required: true, message: this.$t('msg_email'), trigger: "blur" },
          { validator: emailCheck, message: this.$t('msg_eamilFormat'), trigger: "blur" }
        ],
        domains: [
          { validator: domainCheck, message: this.$t('msg_domain_required'), trigger: "change" },
        ],
        dept: [
          { validator: deptCheck, message: this.$t('msg_dept_required'), trigger: "change" }
        ],
      },
      first: true,
      password: "666666qqqq",
      pwdPre: "",
      checked: false,
      accessToken: "",
      searchdata:{
        currpage: 1,
        pagelines: 1000000,
        data:{
          name:"",
          username:''
        }
      },
      domains:[],
      depts:[],
      isOpen:false,//是否开启安全开关
      level:null,//记录当前登陆用户的级别
      domainDisable:false,//当前是新建用户且是域级用户登陆
      deptMust:false,//域级用户登录，新建用户所属部门必填
      isFilter:false,
      headerArr:{}
    };
  },

  methods: {
    onBtnClick(name){
      if(name=='save'){this.onSaveBtnClick('form')}
      else if(name=='back'){this.$emit('exit')}
    },
    changeSelectDoamin(val){
      this.$set(this.content, 'domains', val)
      if(!val){
        this.depts = []
      }else{
        // 请求所属部门的接口
        this.getDept()
      }
      this.$forceUpdate()
    },
    getDept(){
      let params= {
        domainid: this.content.domains[0],
        valid:1,
        superiorid: "",
        currpage: 1,
        pagelines: 10000000,
        orderby: "",
        data:{
          name: "",
        }
      };
      this.$api.getSubDepartments(params, {
        onSucess: resp => {
          this.depts = resp.data.data;
        }
      });
    },
    changeDeveloper(val){
      if(val){
        this.getApplicationsList()
      }
    },
    getApplicationsList(){
      this.$api.getCustomApps({
        onSucess: resp => {
          this.softList = resp.data.data.datas
          let arr=checkHasIdArr(this.softList,this.content.applications)
          this.$set(this.content, 'applications', arr)
        }
      });
    },
    getDomain(){
      this.$api.getDomains(this.searchdata,{
        onSucess: response => {
          this.domains = response.data.data;
          let arr=checkHasIdArr(this.domains.datas,this.content.domains)
          this.changeSelectDoamin(arr)
        }
      });
    },
    processPassword(pw) {
      let Base64 = require("js-base64").Base64;
      var str = Base64.encode(pw);
      if (str.length > 2) {
        var lp = str.substr(0, 2);
        var rp = str.substr(2, str.length);
        pw = rp + lp;
      }
      return pw;
    },
    changePwd(val) {
      if (val !== this.pwdPre) {
        this.password = "";
      } else {
        this.password = "666666qqqq";
      }
    },
    onBackList() {},
    onGenAccessTokenBtnClick() {
      this.$api.genAccessToken(this.content.id, {
        onSucess: resp => {
          if (resp.status == 200 && resp.data && resp.data.errcode == 0) {
            this.accessToken = resp.data.data.accessToken;
          }
          else {
              this.accessToken = "ERROR";
          }
        }
      });
    },
    onSaveBtnClick(formName) {
      let that=this,passwordOrigin=''//记录传过去的密码
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(!this.isFilter){
            if(!this.content.developer && !this.content.superAdmin && !this.content.domainAdmin){
              this.$message.error(this.$t('msg_select_user_type'))
             return false
           }
          }
          if (this.password != "666666qqqq" && this.content.loginpwd) {
            // 判断确认密码与密码是否一致
            if(this.content.loginpwd != this.content.confirmpwd){
              this.$message.error(this.$t('msg_confirm_password_not_same'))
              return false;
            }
            passwordOrigin=this.processPassword(this.content.loginpwd)
          } else if (
            this.password != "666666qqqq" &&
            this.content.loginpwd == ""
          ) {
            this.$message({
              showClose: true,
              message: that.$t('msg_require_password'),
              type: "error"
            });
            return false;
          } else {
            this.content.loginpwd = "666666qqqq";
            passwordOrigin=this.content.loginpwd
          }
        
          let content = {
            name: this.content.name,
            loginno: this.content.loginno,
            password: passwordOrigin,
            email: this.content.email,
            status: this.content.status,
            "issuperadmin": this.content.superAdmin,
            "isdeveloper": this.content.developer,
            "isdomainadmin": this.content.domainAdmin,
            "domains": this.content.domains == null?[]:this.content.domains,
            "applications": this.content.applications == null?[]:this.content.applications,
            "departments": this.content.departments,
            "type":this.content.type==null?"super":this.content.type
          };
          if (this.content.id) {
            //更新

            this.$api.saveSuperUser(
              {
                id: this.content.id,
                data: content
              },
              {
                onSucess: resp => {
                  if (resp.data.errcode == 0) {
                    this.$message({
                      showClose: true,
                      message: this.$t('msg_save_success'),
                      type: "success"
                    });
                    this.password = "666666qqqq";
                    this.$emit("exit");
                  } else {
                    this.$message({
                      showClose: true,
                      message: resp.data.errmsg,
                      type: "error"
                    });
                  }
                },
                onError: resp => {
                  this.$message({
                    showClose: true,
                    message: resp.data.errmsg,
                    type: "false"
                  });
                }
              }
            );
          } else {
            //新建

            this.$api.createSuperUser(
              {
                data: content
              },
              {
                onSucess: resp => {
                  if (resp.data.errcode == 0) {
                    this.$message({
                      showClose: true,
                      message: this.$t('msg_save_success'),
                      type: "success"
                    });
                    this.password = "666666qqqq";
                    this.$emit("exit");
                  } else {
                    this.$message({
                      showClose: true,
                      message: resp.data.errmsg,
                      type: "error"
                    });
                  }
                },
                onError: resp => {
                  this.$message({
                    showClose: true,
                    message: resp.data.errmsg,
                    type: "error"
                  });
                }
              }
            );
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
//修改el-select下拉框样式
.el-select-dropdown__item {
  span{
    max-width: 95%;
    text-overflow: ellipsis;
    overflow: hidden;
    display: inline-block;
  }
}
</style>